package com.yumeng.framework.persistence.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.yumeng.framework.persistence.mybatis.injector.MySqlMethod;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 批量更新
 * @author wxd
 * @date 2021/12/14 20:45
 */
public class UpdateBatchByIds extends AbstractMethod {

    private static final MySqlMethod SQL_METHOD = MySqlMethod.UPDATE_BATCH_BY_IDS;

    public UpdateBatchByIds() {
        super(SQL_METHOD.getMethod());
    }

    /**
     * 注入自定义 MappedStatement
     * "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>"
     *
     * <update id="updateInBatchSelective" parameterType="java.util.List">
     *         <foreach collection="list" item="item" index="index" open="" close="" separator=";">
     *             update t_producerecord_taskinputs
     *             <set >
     *                 <if test="item.produceRecordTaskId != null" >
     *                     produceRecordTaskId = #{item.produceRecordTaskId,jdbcType=BIGINT}
     *                 </if>
     *                 <if test="item.produceRecordId != null" >
     *                     produceRecordId = #{item.produceRecordId,jdbcType=BIGINT}
     *                 </if>
     *                 <if test="item.inputsId != null" >
     *                     inputsId = #{item.inputsId,jdbcType=BIGINT}
     *                 </if>
     *             </set>
     *             where produceRecordTaskInputsId = #{item.produceRecordTaskInputsId,jdbcType=BIGINT}
     *         </foreach>
     * </update>
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        //final String additional = optlockVersion(tableInfo);// + tableInfo.getLogicDeleteSql(true, true)  条件不需要增加逻辑删除字段判断
        final String additional = "";//暂不支持乐观锁
        //"<script>\n%s\n</script>"
        String oneSqlScript = "UPDATE %s %s WHERE %s=#{%s} %s";

        //不考虑框架自带逻辑删除
        boolean isWithLogicDelete = false;//tableInfo.isWithLogicDelete();
        String sqlSet = sqlSet(isWithLogicDelete, false, tableInfo, false, ENTITY, ENTITY_DOT);
        String sql = String.format(oneSqlScript, tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(), ENTITY_DOT + tableInfo.getKeyProperty(), additional);

        sql = String.format(SQL_METHOD.getSql(), SqlScriptUtils.convertForeach(sql, "list", null, ENTITY, SEMICOLON)) ;

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlSource);
    }

}
